package com.example.flshtarvel.component;

import com.example.flshtarvel.entity.Article;
import com.example.flshtarvel.entity.Image;
import com.example.flshtarvel.service.ImageService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;

@Component
public class UploadImage {
    @Autowired
    private ImageService imageService;
//    @Autowired
//    private ImageArticleMapService imageArticleMapService;
    public static  UploadImage uploadImage;

    @PostConstruct
    public  void init(){
        uploadImage = this;
    }

    //上传图片资源
    public void executeUploadImage(MultipartFile[] files, Article article) throws Exception {
        //图片路径字符串
        String imageUrls = "";
        try {
            //上传路径
            String uploadDir = ResourceUtils.getURL("classpath:static/").getPath() + "image/";
            System.out.println("上传的图片");

            int imageLen = files.length;
            for (int i = 0; i < imageLen; i++) {
                MultipartFile file = files[i];
                if (file.isEmpty()) {
                    //文件为空处理
                    System.out.println("文件为空");
                } else {
                    //文件不为空，存进服务器
                    //文件名
                    String fileName = file.getOriginalFilename();
                    System.out.println(fileName);
                    //服务器保存的文件对象
                    File serverFile = new File(uploadDir+fileName);
                    //将上传的文件写入到服务器端文件内
                    file.transferTo(serverFile);

                    //将图片路径存进数据库
                    Image image = new Image();
                    //ImageArticleMap imageArticleMap = new ImageArticleMap();
                    image.setImageName(fileName);
                    image.setImageUrl(uploadDir+fileName);
                    image.setArticleId(article.getArticleId());
                    //存进 图片（image） 数据表
                    uploadImage.imageService.insertImage(image);
                    //imageArticleMap.setImageId(image.getImageId());
                    //imageArticleMap.setArticleId(article.getArticleId());
                    //存进 图片信息映射表（image_article_map）
                    //uploadImage.imageArticleMapService.insertImageArticleMap(imageArticleMap);

                    imageUrls = imageUrls + uploadDir + fileName + ";";


                }
            }
        }catch (Exception e){
            e.printStackTrace();
            System.out.println(imageUrls);
        }

    }
}
